package top.jandmla.shop.config.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import top.jandmla.shop.bean.User;
import top.jandmla.shop.service.UserService;


public class UserRealm  extends AuthorizingRealm {

    @Autowired
    private UserService userService;

//    @Autowired
//    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 权限加载
     * @param principalCollection 认证信息
     * @return 加载结果
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        User user = (User) principalCollection.getPrimaryPrincipal();

//        redisTemplate.opsForList().leftPushAll(user.getUserName(),user);
//        for (RolePojo role : user.getRoleList()) {
//            info.addRole(role.getRoleName());
//
//
//
//            for (Menu menu : role.getMenusList()) {
//                info.addStringPermission(menu.getPermit());
//            }
//        }
        return info;
    }

    /**
     * 登录认证
     * @param token 用户名和密码生成的token
     * @return 认证信息
     * @throws AuthenticationException 登录可能出现的异常
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken userToken = (UsernamePasswordToken) token;
        //根据用户名，查找用户对象（查找过程自己编写service层）
        //此对象会被保存在SecurityUtils.getSubject()中，不建议查询密码
        User user = userService.getUserByName(userToken.getUsername());

        if (user == null)
            return null;
                                    //  保存信息  密码  userRealm名称
        return new SimpleAuthenticationInfo(user,userService.getPasswordById(user.getUserid()),"userRealm");
    }
}
